<?php

chdir(dirname(__FILE__)."/../..");
$path = getcwd();
chdir("../");
$path3 = getcwd();
chdir(dirname(__FILE__));
#debug($path3 , $path2);
include_once $path3."/lib/core.class.php";



class vendors extends IPlugin 
{
    var $color;
    
    function vendors($parent = null)
    {
        IPlugin::IPlugin($parent);
        $this->tplfolder = dirname(__FILE__)."/tpl";
        $this->color = "blue";
    }
    
    function getPluginTag() { return "vendorslist"; }
    function getPluginName() { return "Vendors entity"; }
    function getPluginVersion() { return "1.0.0"; }
    
    function getProperty($p = null)
    {
        if(null == $p)
        {
            return array("MenuBlockTitle", "MenuTitle");
        }
        $result = "";
        switch ($p)
        {
            case "MenuBlockTitle": { return "Online Shop"; } break;
            case "MenuTitle" : { return "Vendors"; } break;
        };
        return $result;
    }

    // ----------------------------------------------------------------------------------
    // --- [ Handling all actions ] -----------------------------------------------------
    // ----------------------------------------------------------------------------------
    function doAction($params)
    {
        if(null != ($result = IPlugin::doAction($params)))
        {
            return $result;
        }
        
        $core = getCoreInstance();
        $arg = $core->getGET();
        
        if("echo" == $arg["action"])
        {
            echo "Vendors: echo: ".$arg["string"];
        }
        if("doDeleteVendor" == $arg["action"] && $arg["id"]>0)
        {
            $db = $core->getProperty("db");
            $fileroot = $core->config["file_root"];
            $iid = str2db($arg['id']);
            $data = $db->getrow("select vendor_imgsmall,vendor_file from vendors where vendor_id='{$iid}'");
            $db->Exec("delete from vendors where vendor_id={$iid}");
            @unlink($fileroot.'/inventory/'.$data['vendor_imgsmall']);
            @unlink($fileroot.'/inventory/'.$data['vendor_file']);
            
        }

        if("doSubmitVendor" == $_POST["action"])
        {
            $core = getCoreInstance();
            $db = $core->getProperty("db"); 
            $fileroot = $core->config["file_root"];                       
            /* Edit EVENT */

            if($_POST['event'] == 'edit'){
            //debug($_FILES);
            
            /* files upload start*/
            if ($_FILES['vendor_imgsmall']['error'] != 4 and $_FILES['vendor_imgsmall']['size'] != 0){
                $catalog_id = $_POST['id'];
                $copy_to = "uploads/".$catalog_id;
                @uploadFile('vendor_imgsmall', "/inventory/".$copy_to."_vendor_logo.jpg");
                if (isne($_FILES['vendor_imgsmall']['tmp_name']))
                $logo = $copy_to."_vendor_logo.jpg";
                $sql = "update vendors set vendor_imgsmall='{$logo}' where vendor_id = '{$_POST['id']}'";
                $db->Exec($sql);
                $sql = '';
            }
            /* files upload end */
            
            /* files upload start*/
            if ($_FILES['vendor_file']['error'] != 4 and $_FILES['vendor_file']['size'] != 0){
                $copy_to = "uploads/vendors_files/".$_POST['id'].'_vendor_file';
                @uploadFile('vendor_file', "/inventory/".$copy_to);
                if (isne($_FILES['vendor_file']['tmp_name']))
                $logo = $copy_to;
                $sql = "update vendors set vendor_file='{$logo}' where vendor_id = '{$_POST['id']}'";
                $db->Exec($sql);
                $sql = '';
            }
            /* files upload end */
            
            $z = $_POST;
            $uid = $z["id"];
            unset($z["action"], $z["id"],$z['event']);

            if (!in_array('vendor_active', array_keys($z))) {
                $z["vendor_active"] = 'N';
            }

            else{
               if ('on' == $z['vendor_active']) 
                $z["vendor_active"] = 'Y';
            }

            $sql = "";
            foreach ($z as $k => $v)
            {
                $sql .= ($sql=="" ? "" : ", ")."{$k} = '".str2db($v)."'";
            }
        
            $sql = "update vendors set {$sql} where vendor_id={$uid}";
            $db->Exec($sql);
            }

            /* ADD EVENT */

            if($_POST['event'] == 'add'){
            //debug($_FILES);
            $z = $_POST;
            $uid = $z["id"];
            unset($z["action"], $z["id"],$z['event']);

            if (!in_array('vendor_active', array_keys($z))) {
                $z["vendor_active"] = 'N';
            }

            else{
               if ('on' == $z['vendor_active']) 
                $z["vendor_active"] = 'Y';
            }

            $sql = "";

            foreach ($z as $k => $v)
            {
                        $keys .=($keys=="" ? "" : ", ")."{$k}";
                        $vars .=($vars=="" ? "" : ", ")."'".str2db($v)."'";
            }
    
            $sql="insert into vendors ({$keys}) values({$vars}) ";
            $catalog_id = $db->Exec($sql);

            /* files upload start*/

            $copy_to = "uploads/".$catalog_id;
            @uploadFile('vendor_imgsmall', "/inventory/".$copy_to."_vendor_logo.jpg");
            if (isne($_FILES['vendor_imgsmall']['tmp_name']))
            $logo = $copy_to."_vendor_logo.jpg";
            $sql = "update vendors set vendor_imgsmall='{$logo}' where vendor_id = '{$catalog_id}'";
            $db->Exec($sql);
            $sql = '';
            /* files upload end */
            
            /* files upload start*/

            $copy_to = "uploads/vendors_files/".$catalog_id.'_vendor_file';
            @uploadFile('vendor_file', "/inventory/".$copy_to);
            if (isne($_FILES['vendor_file']['tmp_name']))
            $file = $copy_to;
            $sql = "update vendors set vendor_file='{$file}' where vendor_id = '{$catalog_id}'";
            $db->Exec($sql);
            $sql = '';
            /* files upload end */
                    
            unset($_POST);          

            }
        }
        
        return true;
    }
    
    // ----------------------------------------------------------------------------------
    // --- [ Render pages ] -------------------------------------------------------------
    // ----------------------------------------------------------------------------------
    function Render($params)
    {
        global $_G;
        if(null != ($result = IPlugin::Render($params)))
        {
            return $result;
        }
        
        $core = getCoreInstance();
        $render = $core->framework->smarty;
        $render->assign("baseurl", "?".$this->getURL()."&page=".$_G["page"]);
        $fileroot = $core->config["file_root"];
        $httproot = $core->config["http_root"];
        $page = "";

        switch ($_G["page"]) {
            case "add":
                $page = $this->renderVendorEditAdd($render,'add');
                break;

            case "edit":
                $page = $this->renderVendorEditAdd($render,'edit');
                break;
            
            case "statistic":
                $page = $this->renderVendorStatistic($render);
                break;
                        
            default:
                $page = $this->renderVendorstList($render);
                break;
        }

        return $render->fetch("file:".$this->tplfolder."/".$page);
    }


    // ----------------------------------------------------------------------------------
    // --- [ Generate Customers List ] --------------------------------------------------
    // ----------------------------------------------------------------------------------
    
/**
 * Returns html <img src=...> code with image if all ok
 *
 * @param 'uploads/imp1_1_1.jpg' $db_path
 * @param 'image alter text' $alt
 * @param core $core
 * @return array (status,result)
 */
    function my_getimage($db_path,$alt,$core){
        $fileroot = $core->config["file_root"];
        $httproot = $core->config["http_root"];
        $img = $db_path;
        
        if('' != $img and 'img/no_image' != $img 
        and file_exists($fileroot.'/inventory/'.$img)){
           $v_img = $httproot.'inventory/'.$img;
           $v_img_html = $v_img = "<img src='".$v_img."' border='0' alt='{$alt}'>";
           $s = 'ok';

        }
        elseif ('' == $img or 'img/no_image.jpg' == $img or 
        !file_exists($fileroot.'inventory/'.$img)) {
           $v_img_html = $v_img = "<img src='".$httproot."img/no_image.jpg' border='0' alt='{$data[vendor_name]} Logo'>";
           $s = 'empty';
           
        }
        else{
           $v_img_html = 'Corrupt image data';
           $s = 'error'; 
        }
        
        $r = array('Status' => $s, 'result' => $v_img_html);
        return $r;
    }

    
    
    function cb_rndCL($data)
    {


        
        $core = getCoreInstance();
        $fileroot = $core->config["file_root"];
        $httproot = $core->config["http_root"];
        $img = $data["vendor_imgsmall"];
        #debug($img);
        if('' != $img and 'no_image' != $img 
        and file_exists($fileroot.'/inventory/'.$img)){
           $v_img = $httproot.'inventory/'.$img;
           $v_img_html = $v_img = "<img src='".$v_img."' border='0' alt='{$data[vendor_name]} Logo'>";

        }
        elseif ('' == $img or 'no_image.jpg' == $img or 
        !file_exists($fileroot.'inventory/'.$img)) {
           $v_img_html = $v_img = "<img src='".$httproot."img/no_image.jpg' border='0' alt='{$data[vendor_name]} Logo'>";
           
        }
        else{
           $v_img_html = 'Corrupt image data'; 
        }
        #debug($v_img_html,"11111111111");
        $dt = array(
                array($data["vendor_id"], "align=\"center\""),
                array($data["vendor_name"], "align=\"left\""),
                array($data["vendor_description"], "align=\"left\""),
                array($v_img_html, "align=\"left\""),
                array($data["vendor_active"], "align=\"center\"" ),
                array("<a href=\"?".$this->getURL()."&page=edit&id={$data[vendor_id]}\">edit</a>&nbsp;&nbsp;<a href=\"?".$this->getURL()."&action=doDeleteVendor&id={$data[vendor_id]}\">delete</a>","align=\"center\""),
                );
        return $dt;
    }

    function renderVendorstList(&$render)
    {
        $core = getCoreInstance();
        $db = $core->getProperty("db");
        $pg = &$core->getSnippet("paginator");

        $params = array(
                    "cb_class" => &$this,
                    "cb_func" => cb_rndCL,
                    "urlbase" => $this->getURL(),
                    "caption" => "Vendors",
                    "emptymsg" => "<center> No vendors added </center>",
                    "header" => array("ID", "Vendor Name", "Vendor Description", "Vendor Logo", 'IsActiveStatus' , "Actions"),
                    "items" => "",
                    "source" => "sql", // -- sql, array
                    "sql_items" => "select vendor_id,vendor_name,vendor_description,vendor_imgsmall,vendor_active from vendors where vendor_id>0",
                    "sql_count" => "select count(*) from vendors where vendor_id>0",
                    "ippg" => 15, // -- items per page
                    "nppv" => 5, // -- number pages per view
                    );

        $HTML = $pg->Render($params);
        $render->assign("vendors", $HTML);
        $render->assign('add_url',$this->getURL());
        return "vendorslist.tpl.php";
    }
    
    function renderVendorStatistic(&$render)
    {
        $core = getCoreInstance();
        $db = $core->getProperty("db");
        
        $rating_vendors=$db->getall("select vendor_id,vendor_name,sum(rating) as sum_rating from vendors v left join catalog c on v.vendor_id=c.owned_by_vendor group by vendor_name order by sum_rating desc");
        $rating_vendors=arraydb2str($rating_vendors);
        $render->assign("rating_vendors", $rating_vendors);
        foreach ($rating_vendors as $v) $sum+=$v[sum_rating];
        if ($sum==0) $sum=1;
        $render->assign("rating_sum", $sum);
        $render->assign('add_url',$this->getURL());
        return "vendorsstatistic.tpl.php";
    }
    
    function renderVendorEditAdd(&$render,$event)
    {
        $core = getCoreInstance();
        $db = $core->getProperty("db");
        $httproot = $core->config["http_root"];
        $render->assign("hroot", $httproot);
        $uid = str2db($_GET["id"]);
     
        $render->assign("url", "?".$this->getURL());
        if($event != 'add'){
        $render->assign("id", $uid);
        $render->assign("usr", $db->getRow("select * from vendors where vendor_id={$uid}"));
                   }
        $render->assign("evenval", $event);


        return "vendoredit.tpl.php";
    }
};


?>